package cn.edu.hqu.cst.android.ljc.ex4;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {
    private int count = 0;
    private boolean quit = false;
    private MyServiceBinder myServiceBinder = new MyServiceBinder();
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(!quit){//如果 service 启动每秒钟 count++，如果 quit 为真则退出
                    try {
                        Thread.sleep(1000);//线程休眠1秒钟
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    MyService.this.count++;
                }
            }
        }).start();//开启线程
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        quit = true;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return myServiceBinder;
    }

    class MyServiceBinder extends Binder {
        public int getCount(){
            return MyService.this.count;
        }
    }
}